<?php

namespace Net;

require_once "Event.php";

trait EventBaseTrait {
    protected $_handles = [];
    
    public function on($type, $callback) {
        if(is_callable($callback)) {
            $this->_handles['on_' . $type][] = $callback;
        }
        
        return $this;
    }
    
    public function before($type, $callback) {
        if(is_callable($callback)) {
            $this->_handles['before_' . $type][] = $callback;
        }
        
        return $this;
    }
    
    public function triggerOn($type, $params=[]) {
        $callbacks = $this->_handles['on_' . $type];
        $event = new Event($type, 'on', $params);
        
        foreach ((array)$callbacks as $callback) {
            $callback($event);
            
            if($event->isStopTransmit()) {
                return $event;
            }
        }
        
        return $event;
    }
    
    public function triggerBefore($type, $params) {
        $callbacks = $this->_handles['before_' . $type];
        $event = new Event($type, 'before', $params);
        
        foreach ((array)$callbacks as $callback) {
            call_user_func_array($callback, [$event]);
            
            if($event->isStopTransmit()) {
                return $event;
            }
        }
        
        return $event;
    }
}